package org.jeecg.modules.flower.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.mapper.*;
import org.jeecg.modules.flower.service.IFlowerStorehouseService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecg.modules.flower.service.IFlowerTagPrintService;
import org.jeecg.modules.flower.service.ITFlowerTagInMain2Service;
import org.jeecg.modules.flower.util.CommonUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 批量入库表主表
 * @Author: jeecg-boot
 * @Date: 2022-07-22
 * @Version: V1.0
 */
@Service
public class TFlowerTagInMain2ServiceImpl extends ServiceImpl<TFlowerTagInMain2Mapper, TFlowerTagInMain2> implements ITFlowerTagInMain2Service {

    @Autowired
    private TFlowerTagInMain2Mapper tFlowerTagInMain2Mapper;
    @Autowired
    private TFlowerTagIn2Mapper tFlowerTagIn2Mapper;

    @Autowired
    private FlowerStorehouseMapper flowerStorehouseMapper;

    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;
    @Autowired
    private IFlowerTagBookService flowerTagBookService;

    @Autowired
    private FlowerTagPrintMapper flowerTagPrintMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(TFlowerTagInMain2 tFlowerTagInMain2, List<TFlowerTagIn2> tFlowerTagIn2List) {
        //自动生成出库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateNo = simpleDateFormat.format(new Date());
        String refex = "CH-RK-" + dateNo;
        LambdaQueryWrapper<TFlowerTagInMain2> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(TFlowerTagInMain2::getNo, refex);
        lambdaQueryWrapper.orderByDesc(TFlowerTagInMain2::getNo);
        List<TFlowerTagInMain2> list = this.list(lambdaQueryWrapper);
        String oldNo = "";
        if (list.size() > 0) {
            oldNo = list.get(0).getNo();
        }
        String no1 = CommonUtil.getNo("CH-RK-", oldNo, 5);
        tFlowerTagInMain2.setNo(no1);//自动生成ru库单号

        if (tFlowerTagInMain2.getSortTime() == null) {
            tFlowerTagInMain2.setSortTime(new Date());
        }
        if (StringUtils.isBlank(tFlowerTagInMain2.getStorehouse())) {
            throw new RuntimeException("库房为空，请选择库房！");
        }
        LambdaQueryWrapper<FlowerStorehouse> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FlowerStorehouse::getCode, tFlowerTagInMain2.getStorehouse());
        List<FlowerStorehouse> flowerStorehouses = flowerStorehouseMapper.selectList(lambdaQueryWrapper2);
        if (flowerStorehouses.size() == 0) {
            throw new RuntimeException("库房的成本中心为空，请选择重新选择库房！");
        }
        tFlowerTagInMain2.setState(0);
        tFlowerTagInMain2.setCost(flowerStorehouses.get(0).getCost());
        tFlowerTagInMain2Mapper.insert(tFlowerTagInMain2);

        for (TFlowerTagIn2 flowerTagIn : tFlowerTagIn2List) {
            //外键设置
            flowerTagIn.setMainid(tFlowerTagInMain2.getId());
            flowerTagIn.setSourceBase(tFlowerTagInMain2.getSourceBase());
            flowerTagIn.setSourceGreenhouse(tFlowerTagInMain2.getSourceGreenhouse());
            flowerTagIn.setStorehouse(tFlowerTagInMain2.getStorehouse());
            flowerTagIn.setCost(tFlowerTagInMain2.getCost());
            flowerTagIn.setProductionId(tFlowerTagInMain2.getProductionId());
            flowerTagIn.setSortTime(tFlowerTagInMain2.getSortTime());
            tFlowerTagIn2Mapper.insert(flowerTagIn);//--并保存子表数据
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain2(TFlowerTagInMain2 tFlowerTagInMain2, List<TFlowerTagIn2> tFlowerTagIn2List) {
        //自动生成出库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateNo = simpleDateFormat.format(new Date());
        String refex = "CH-RK-" + dateNo;
        LambdaQueryWrapper<TFlowerTagInMain2> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(TFlowerTagInMain2::getNo, refex);
        lambdaQueryWrapper.orderByDesc(TFlowerTagInMain2::getNo);
        List<TFlowerTagInMain2> list = this.list(lambdaQueryWrapper);
        String oldNo = "";
        if (list.size() > 0) {
            oldNo = list.get(0).getNo();
        }
        String no1 = CommonUtil.getNo("CH-RK-", oldNo, 5);
        tFlowerTagInMain2.setNo(no1);//自动生成ru库单号

        if (tFlowerTagInMain2.getSortTime() == null) {
            tFlowerTagInMain2.setSortTime(new Date());
        }
        if (StringUtils.isBlank(tFlowerTagInMain2.getStorehouse())) {
            throw new RuntimeException("库房为空，请选择库房！");
        }
        LambdaQueryWrapper<FlowerStorehouse> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FlowerStorehouse::getCode, tFlowerTagInMain2.getStorehouse());
        List<FlowerStorehouse> flowerStorehouses = flowerStorehouseMapper.selectList(lambdaQueryWrapper2);
        if (flowerStorehouses.size() == 0) {
            throw new RuntimeException("库房的成本中心为空，请选择重新选择库房！");
        }
        tFlowerTagInMain2.setState(0);
        tFlowerTagInMain2.setCost(flowerStorehouses.get(0).getCost());
        tFlowerTagInMain2Mapper.insert(tFlowerTagInMain2);

        for (TFlowerTagIn2 flowerTagIn : tFlowerTagIn2List) {
            //外键设置
            flowerTagIn.setMainid(tFlowerTagInMain2.getId());
            flowerTagIn.setSourceBase(tFlowerTagInMain2.getSourceBase());
            flowerTagIn.setSourceGreenhouse(tFlowerTagInMain2.getSourceGreenhouse());
            flowerTagIn.setStorehouse(tFlowerTagInMain2.getStorehouse());
            flowerTagIn.setCost(tFlowerTagInMain2.getCost());
            flowerTagIn.setProductionId(tFlowerTagInMain2.getProductionId());
            flowerTagIn.setSortTime(tFlowerTagInMain2.getSortTime());
            tFlowerTagIn2Mapper.insert(flowerTagIn);//--并保存子表数据
        }


        sure(tFlowerTagInMain2.getId());//自动确认收货

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(TFlowerTagInMain2 tFlowerTagInMain2, List<TFlowerTagIn2> tFlowerTagIn2List) {
        String inType = tFlowerTagInMain2.getInType();
        if("扫码入库".equals(inType)){
            throw new RuntimeException("扫码入库的不允许修改！");
        }
        String id = tFlowerTagInMain2.getId();
        Integer state1 = tFlowerTagInMain2.getState();
        if (state1 != 0) {
            throw new RuntimeException("已审批过的入库单不可修改！");
        }
        if (StringUtils.isBlank(tFlowerTagInMain2.getStorehouse())) {
            throw new RuntimeException("库房为空，请选择库房！");
        }
        LambdaQueryWrapper<FlowerStorehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerStorehouse::getCode, tFlowerTagInMain2.getStorehouse());
        List<FlowerStorehouse> flowerStorehouses = flowerStorehouseMapper.selectList(lambdaQueryWrapper);
        if (flowerStorehouses.size() == 0) {
            throw new RuntimeException("库房的成本中心为空，请选择重新选择库房！");
        }
        tFlowerTagInMain2.setCost(flowerStorehouses.get(0).getCost());

        //判断是否已经存在出库，如果存在则不允许修改数量
        List<TFlowerTagIn2> tFlowerTagIn2sOld = tFlowerTagIn2Mapper.selectByMainId(id);
        for (TFlowerTagIn2 flowerTagIn2 : tFlowerTagIn2sOld) {
            //判断是否已经存在出库，如果存在则不允许修改数量
            LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
            taginfoQuery.eq(FlowerTagInfo::getInId, flowerTagIn2.getId());
            List<FlowerTagInfo> taginfoList = flowerTagInfoService.list(taginfoQuery);
            for (FlowerTagInfo tagInfo : taginfoList) {
                String state = tagInfo.getState();
                if (!"1".equals(state)) {
                    log.error("该入库的产品已经出库或删除的数据，不能在修改了！");
                    throw new RuntimeException("该入库的产品已经出库或删除的数据，不能在修改了！");
                }
            }
        }
        //1.先删除子表数据
        tFlowerTagIn2Mapper.deleteByMainId(tFlowerTagInMain2.getId());
        tFlowerTagInMain2Mapper.updateById(tFlowerTagInMain2);
        for (TFlowerTagIn2 flowerTagIn : tFlowerTagIn2List) {
            //外键设置
            flowerTagIn.setMainid(tFlowerTagInMain2.getId());
            flowerTagIn.setSourceBase(tFlowerTagInMain2.getSourceBase());
            flowerTagIn.setSourceGreenhouse(tFlowerTagInMain2.getSourceGreenhouse());
            flowerTagIn.setStorehouse(tFlowerTagInMain2.getStorehouse());
            flowerTagIn.setCost(tFlowerTagInMain2.getCost());
            flowerTagIn.setProductionId(tFlowerTagInMain2.getProductionId());
            flowerTagIn.setSortTime(tFlowerTagInMain2.getSortTime());
            tFlowerTagIn2Mapper.insert(flowerTagIn);//--并保存子表数据
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        TFlowerTagInMain2 tFlowerTagInMain2 = tFlowerTagInMain2Mapper.selectById(id);
        Integer state1 = tFlowerTagInMain2.getState();
        if (state1 == -2) {
            throw new RuntimeException("已经删除过了！");
        }
        if (state1 != 0) {
            throw new RuntimeException("已审批过的入库单不可删除！");
        }
        List<TFlowerTagIn2> tFlowerTagIn2s = tFlowerTagIn2Mapper.selectByMainId(id);
        for (TFlowerTagIn2 flowerTagIn2 : tFlowerTagIn2s) {
            //判断是否已经存在出库，如果存在则不允许修改数量
            LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
            taginfoQuery.eq(FlowerTagInfo::getInId, flowerTagIn2.getId());
            List<FlowerTagInfo> taginfoList = flowerTagInfoService.list(taginfoQuery);
            for (FlowerTagInfo tagInfo : taginfoList) {
                String state = tagInfo.getState();
                if (!"1".equals(state)) {
                    log.error("该入库的产品已经出库或删除的数据，不能在修改了！");
                    throw new RuntimeException("该入库的产品已经出库或删除的数据，不能在修改了！");
                }
            }
//            //不存在出库，则删除台账
//            flowerTagInfoService.remove(taginfoQuery);
        }
        tFlowerTagInMain2.setId(id);
        tFlowerTagInMain2.setState(-2);
        tFlowerTagInMain2Mapper.updateById(tFlowerTagInMain2);//逻辑删除
//        tFlowerTagIn2Mapper.deleteByMainId(id);
//        tFlowerTagInMain2Mapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            TFlowerTagInMain2 tFlowerTagInMain2 = tFlowerTagInMain2Mapper.selectById(id);
            Integer state1 = tFlowerTagInMain2.getState();
            if (state1 == -2) {
                throw new RuntimeException(tFlowerTagInMain2.getNo() + "已经删除过了！");
            }
            if (state1 != 0) {
                throw new RuntimeException("已审批过的入库单不可删除！");
            }
            List<TFlowerTagIn2> tFlowerTagIn2s = tFlowerTagIn2Mapper.selectByMainId(id.toString());
            for (TFlowerTagIn2 flowerTagIn2 : tFlowerTagIn2s) {
                //判断是否已经存在出库，如果存在则不允许修改数量
                LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
                taginfoQuery.eq(FlowerTagInfo::getInId, flowerTagIn2.getId());
                List<FlowerTagInfo> taginfoList = flowerTagInfoService.list(taginfoQuery);
                for (FlowerTagInfo tagInfo : taginfoList) {
                    String state = tagInfo.getState();
                    if (!"1".equals(state)) {
                        log.error("该入库的产品已经出库或删除的数据，不能在修改了！");
                        throw new RuntimeException("该入库的产品已经出库或删除的数据，不能在修改了！");
                    }
                }
                //不存在出库，则删除台账
                flowerTagInfoService.remove(taginfoQuery);
            }
            tFlowerTagInMain2.setId(id.toString());
            tFlowerTagInMain2.setState(-2);
            tFlowerTagInMain2Mapper.updateById(tFlowerTagInMain2);//逻辑删除
//            tFlowerTagIn2Mapper.deleteByMainId(id.toString());
//            tFlowerTagInMain2Mapper.deleteById(id);

        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void createTaginfos(TFlowerTagInMain2 tFlowerTagInMain2) {
        LoginUser sysUser = new LoginUser();
        try {
            sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            sysUser.setRealname("自动扫码");
            sysUser.setUsername("自动扫码");
        }

        tFlowerTagInMain2.setSortTime(new Date());//更新审核分拣时间
        tFlowerTagInMain2.setState(1);
        tFlowerTagInMain2.setBaseCadre(sysUser.getRealname());
        tFlowerTagInMain2.setBaseCadreTime(new Date());
        this.updateById(tFlowerTagInMain2);

        List<TFlowerTagIn2> tFlowerTagIn2List = tFlowerTagIn2Mapper.selectByMainId(tFlowerTagInMain2.getId());
        if (tFlowerTagIn2List == null || tFlowerTagIn2List.size() == 0) {
            throw new RuntimeException("请先添加需要入库的品种数据！");
        }

        //批量生成标签台账表数据
        String sourceBase = tFlowerTagInMain2.getSourceBase();
        String sourceGreenhouse = tFlowerTagInMain2.getSourceGreenhouse();
        String storehouse = tFlowerTagInMain2.getStorehouse();
        String cost = tFlowerTagInMain2.getCost();

        List<FlowerTagInfo> listin = new ArrayList<>();
        for (TFlowerTagIn2 flowerTagIn : tFlowerTagIn2List) {
            String inId = flowerTagIn.getId();
            String productionId = flowerTagIn.getProductionId();
            String variety = flowerTagIn.getVariety();
            String varietyCode = flowerTagIn.getVarietyCode();
            String classes = flowerTagIn.getClasses();
            Date sortTime = flowerTagIn.getSortTime();
            String packingSpecifications = flowerTagIn.getPackingSpecifications();//打包规格
            String flowerPoleLength = flowerTagIn.getFlowerPoleLength();
            BigDecimal tagNum = flowerTagIn.getTagNum();//入库数量

            if (tagNum.compareTo(BigDecimal.ZERO) < 0) {
                throw new RuntimeException("入库数量不可进行小于0");
            }
            FlowerTagInfo flowerTagInfo = new FlowerTagInfo();
            flowerTagInfo.setInId(inId);
            flowerTagInfo.setSourceBase(sourceBase);
            flowerTagInfo.setSourceGreenhouse(sourceGreenhouse);
            flowerTagInfo.setStorehouse(storehouse);
            flowerTagInfo.setCost(cost);
            flowerTagInfo.setProductionId(productionId);
            flowerTagInfo.setVariety(variety);
            flowerTagInfo.setClasses(classes);
            flowerTagInfo.setVarietyCode(varietyCode);
            flowerTagInfo.setSortTime(sortTime);
            flowerTagInfo.setStockInTime(new Date());
            flowerTagInfo.setStockInUser(sysUser.getUsername());
            flowerTagInfo.setPackingSpecifications(packingSpecifications);
            flowerTagInfo.setFlowerPoleLength(flowerPoleLength);
            flowerTagInfo.setState("1");//默认全部是入库的
            flowerTagInfo.setTagNum(tagNum);
            listin.add(flowerTagInfo);
        }
        flowerTagInfoService.saveBatch(listin);

        flowerTagBookService.inBooks(tFlowerTagInMain2.getId(),true);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("回撤库存不足,不可编辑和删除！");
        }
    }

    /**
     * 批量入库表主表-审核确认入库
     *
     * @return java.lang.String
     * @descriptionauthor
     * @author gf
     * 2022-12-7 13:47
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sure(String id) {
        String rest = "审核入库成功";
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("数据为空，请重新打开需要审核的数据弹窗！");
        }
        TFlowerTagInMain2 tFlowerTagInMain2 = this.getById(id);
        Integer state1 = tFlowerTagInMain2.getState();
        if (state1 != 0) {
            throw new RuntimeException("已审批过了！");
        }
        String inType = tFlowerTagInMain2.getInType();
        if (StringUtils.isBlank(inType)) {
            tFlowerTagInMain2.setInType("手工入库");
        }
        createTaginfos(tFlowerTagInMain2);
        return rest;
    }

    /**
     * 批量入库表主表-审核确认入库--撤销
     *
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor
     * @author gf
     * 2022-12-7 13:47
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sureBack(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("数据为空，请重新打开需要审核的数据弹窗！");
        }
        TFlowerTagInMain2 flowerTagInMain2 = this.getById(id);
        Integer state1 = flowerTagInMain2.getState();
        if (state1 != 1) {
            throw new RuntimeException("还未审批，不可撤销！");
        }
        String inType = flowerTagInMain2.getInType();

        flowerTagInMain2.setState(0);
        flowerTagInMain2.setBaseCadre("");
        flowerTagInMain2.setBaseCadreTime(null);
        this.updateById(flowerTagInMain2);

        //判断是否已经存在出库，如果存在则不允许修改数量
        List<TFlowerTagIn2> tFlowerTagIn2sOld = tFlowerTagIn2Mapper.selectByMainId(id);

        flowerTagBookService.inBooks( id ,false);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("回撤库存不足,不可编辑和删除！");
        }
        removeTagInfos(tFlowerTagIn2sOld);

        if("扫码入库".equals(inType)){
            delMain(id);
        }
        return "撤销审核成功";
    }

    /**
     * @return void
     * @descriptionauthor 删除入库单的台账数据，
     * @author gf
     * 2023-1-10 16:02
     * [tFlowerTagIn2sOld]
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeTagInfos(List<TFlowerTagIn2> tFlowerTagIn2sOld) {
        List<String> tagids = new ArrayList<>();
        List<String> printIDS = new ArrayList<>();
        for (TFlowerTagIn2 flowerTagIn2 : tFlowerTagIn2sOld) {
            if(StringUtils.isNotBlank(flowerTagIn2.getTagprintId())) {
                printIDS.add(flowerTagIn2.getTagprintId());
            }
            //判断是否已经存在出库，如果存在则不允许修改数量
            LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
            taginfoQuery.eq(FlowerTagInfo::getInId, flowerTagIn2.getId());
            List<FlowerTagInfo> taginfoList = flowerTagInfoService.list(taginfoQuery);
            for (FlowerTagInfo tagInfo : taginfoList) {
                String state = tagInfo.getState();
                if (!"1".equals(state)) {
                    log.error("该入库的产品已经出库或删除的数据，不能在修改了！");
                    throw new RuntimeException(tagInfo.getVariety() + "该入库的产品已经出库或删除的数据，不能在修改了！");
                }
                tagids.add(tagInfo.getId());
            }
            //不存在出库，则删除台账
//            flowerTagInfoService.remove(taginfoQuery);//2023年1月9日16:59:28   郭绯改为根据id来删除，避免库存台账中数据 多余
        }
        if (tagids.size() > 0) {
            //2023年1月9日16:59:28   郭绯改为根据id来删除，避免库存台账中数据 多余
            QueryWrapper<FlowerTagInfo> flowerTagInfoWrapper = new QueryWrapper<>();
            flowerTagInfoWrapper.in("id", tagids);
            flowerTagInfoService.remove(flowerTagInfoWrapper);
        }

        //更改 标签表状态
        if (printIDS.size() > 0) {
            UpdateWrapper<FlowerTagPrint> flowerTagInfoWrapper = new UpdateWrapper<>();
            flowerTagInfoWrapper.in("id", printIDS);
            flowerTagInfoWrapper.set("state", 0);
            flowerTagInfoWrapper.set("in_time", null);
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            flowerTagInfoWrapper.set("in_people", sysUser.getRealname() + "删除");
            FlowerTagPrint flowerTagPrint = new FlowerTagPrint();
            flowerTagPrintMapper.update(flowerTagPrint, flowerTagInfoWrapper);
        }
    }
}
